//
//  ViewController.m
//  AAPowerApp
//
//  Created by 李恺然 on 2018/11/24.
//  Copyright © 2018 Karl. All rights reserved.
//

#import "ViewController.h"
#import "AppManager.h"
#import "UIView+YYAdd.h"
#import "ViewController+JSNative.h"
#import "OperationView.h"
#import "ConfigModel.h"

@interface ViewController ()<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (nonatomic) NSURL *currentUrl;
@property (nonatomic) UIButton *funcBtn;
@property (nonatomic) UIButton *orienBtn;
@property (nonatomic) BOOL portraitOrientation;
@property (nonatomic) OperationView *operationView;
@property (nonatomic) UIView *leftMaskView;
@property (nonatomic) UIView *rightMaskView;
@property (nonatomic, assign) CGFloat operationBaseMargin;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupViews];
    [self loadHomepage];
}

- (void)setupViews{
    [self.view addSubview:self.webView];
//    [self.view addSubview:self.funcBtn];
    [self.view addSubview:self.operationView];
    [self.view addSubview:self.leftMaskView];
    [self.view addSubview:self.rightMaskView];
}

- (UIView *)leftMaskView{
    if (!_leftMaskView) {
        _leftMaskView = [UIView new];
        _leftMaskView.backgroundColor = [UIColor colorWithRed:31./255. green:31./255. blue:31./255. alpha:1.];
    }
    return _leftMaskView;
}

- (UIView *)rightMaskView{
    if (!_rightMaskView) {
        _rightMaskView = [UIView new];
        _rightMaskView.backgroundColor = [UIColor colorWithRed:31./255. green:31./255. blue:31./255. alpha:1.];
    }
    return _rightMaskView;
}

- (void)viewSafeAreaInsetsDidChange{
    [super viewSafeAreaInsetsDidChange];
    if (@available(iOS 11.0, *)) {
        UIEdgeInsets safeAreaInsets = self.view.safeAreaInsets;
        CGFloat left = safeAreaInsets.left;
        _leftMaskView.size = CGSizeMake(left, self.view.height);
        _leftMaskView.top = 0;
        _leftMaskView.left = 0;
        CGFloat right = safeAreaInsets.right;
        _operationBaseMargin = right;
        _rightMaskView.size = CGSizeMake(right, self.view.height);
        _rightMaskView.top = 0;
        _rightMaskView.right = self.view.width;
        _operationView.left = self.view.width - _operationBaseMargin - 22;
    }
}

- (void)loadHomepage{
    NSString *urlString = [self getHomepageUrl];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    [request addValue:[AppManager sharedManager].cookieStr forHTTPHeaderField:@"Cookie"];
    [_webView loadRequest:request];
}

- (NSString *)getHomepageUrl{
    if ([AppManager sharedManager].config) {
        switch ([AppManager sharedManager].userLanguage) {
            case UserLanguageEng:
                       return [AppManager sharedManager].config.web_url_en;
                   case UserLanguageChn:
                       return [AppManager sharedManager].config.web_url_cn;
        }
    }
    return @"http://aa.mysmartedu.com.cn/index.php/Personal/startindex";
}

- (void)showOperation{
    
    [UIView animateWithDuration:0.25 animations:^{
        self.operationView.bottom = self.view.height - 34;
    }];
}

- (void)loadFuncpage{
    //http://aa.mysmartedu.com.cn/aapowerapi/demo.html
    NSString *urlString = @"http://aa.mysmartedu.com.cn/aapowerapi/demo.html";
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    [request addValue:[AppManager sharedManager].cookieStr forHTTPHeaderField:@"Cookie"];
    [_webView loadRequest:request];
}

- (void)orienAction:(id)sender{
    _portraitOrientation = !_portraitOrientation;
    if (_portraitOrientation) {
        [[UIDevice currentDevice]setValue:@(UIDeviceOrientationPortrait) forKey:@"orientation"];
    }else{
        [[UIDevice currentDevice]setValue:@(UIDeviceOrientationLandscapeLeft) forKey:@"orientation"];
    }
}

- (UIButton *)funcBtn{
    if (!_funcBtn) {
        _funcBtn = [UIButton new];
        [_funcBtn setBackgroundColor:[UIColor colorWithWhite:1.0 alpha:0.5]];
        _funcBtn.width = 44;
        _funcBtn.height = 44;
        _funcBtn.layer.masksToBounds = YES;
        _funcBtn.layer.cornerRadius = 22;
        _funcBtn.centerY = self.view.height / 2;
        _funcBtn.left = 15;
        [_funcBtn addTarget:self action:@selector(showOperation) forControlEvents:UIControlEventTouchUpInside];
    }
    return _funcBtn;
}

- (OperationView *)operationView{
    if (!_operationView) {
        _operationView = [[OperationView alloc] initWithFrame:CGRectZero];
        _operationView.centerY = self.view.height / 2;
        _operationView.left = self.view.width - _operationBaseMargin - 22;
        __weak typeof(self) weakSelf = self;
        _operationView.showBlock = ^{
            
            if (weakSelf.operationView.right == weakSelf.view.width - weakSelf.operationBaseMargin) {
                [UIView animateWithDuration:0.25 animations:^{
                    weakSelf.operationView.right += 44;
                }];
            }else if (weakSelf.operationView.left == weakSelf.view.width - weakSelf.operationBaseMargin - 22){
                [UIView animateWithDuration:0.25 animations:^{
                    weakSelf.operationView.right = weakSelf.view.width - weakSelf.operationBaseMargin;
                }];
            }else{
                return ;
            }
        };
        _operationView.refreshBlock = ^{
            [weakSelf.webView reload];
        };
        _operationView.goFrontBlock = ^{
            [weakSelf.webView goForward];
        };
        _operationView.goBackBlock = ^{
            [weakSelf.webView goBack];
        };
        _operationView.stopBlock = ^{
            [weakSelf.webView stopLoading];
        };
        _operationView.funcBlock = ^{
            [weakSelf loadFuncpage];
        };
        _operationView.homepageBlock = ^{
            [weakSelf loadHomepage];
        };
        _operationView.logoutBlock = ^{
            [[AppManager sharedManager] logoutWithCompetedHandler:NULL];
        };
    }
    return _operationView;
}

- (UIButton *)orienBtn{
    if (!_orienBtn) {
        _orienBtn = [UIButton new];
        [_orienBtn setBackgroundColor:[UIColor whiteColor]];
        [_orienBtn setTitle:@"Orientation" forState:UIControlStateNormal];
        [_orienBtn setTitleColor:[UIColor darkTextColor] forState:UIControlStateNormal];
        _orienBtn.width = 100;
        _orienBtn.height = 100;
        [_orienBtn sizeToFit];
        _orienBtn.top = _funcBtn.bottom + 15;
        _orienBtn.left = 15;
        [_orienBtn addTarget:self action:@selector(orienAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _orienBtn;
}

- (WKWebView *)webView{
    if (!_webView) {
        WKWebViewConfiguration *webConfig = [[WKWebViewConfiguration alloc] init];
        webConfig.preferences = [[WKPreferences alloc] init];
        webConfig.preferences.minimumFontSize = 10;
        webConfig.preferences.javaScriptEnabled = YES;
        webConfig.preferences.javaScriptCanOpenWindowsAutomatically = NO;
        webConfig.processPool = [[WKProcessPool alloc] init];
        WKUserContentController* userContentController = WKUserContentController.new;
        WKUserScript * cookieScript = [[WKUserScript alloc]
                                       initWithSource: [AppManager sharedManager].cookieStr injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
        [userContentController addUserScript:cookieScript];
        webConfig.userContentController = userContentController;
        
        _webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:webConfig];
        _webView.backgroundColor = [UIColor groupTableViewBackgroundColor];
        _webView.allowsBackForwardNavigationGestures = YES;
        _webView.navigationDelegate = self;
        _webView.UIDelegate = self;
        _webView.scrollView.maximumZoomScale =1.0;
        _webView.scrollView.minimumZoomScale = 1.0;
        _webView.scrollView.bouncesZoom = NO;
        _webView.scrollView.bounces = NO;
        [self setupScriptMessageHandler:self
                                webView:_webView];
        
    }
    return _webView;
}

#pragma mark -

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    if (userContentController != _webView.configuration.userContentController) {
        return;
    }
    [self dealJSMethod:message];
}

#pragma mark - WKNavigationDelegate
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    
}
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    
}
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
    
}
// 接收到服务器跳转请求之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
    
}
//在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
//允许跳转
    decisionHandler(WKNavigationResponsePolicyAllow);
//不允许跳转
}
// 在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    NSURL *URL = navigationAction.request.URL;
    if (![[NSString stringWithFormat:@"%@",URL] isEqualToString:[NSString stringWithFormat:@"%@",self.currentUrl]]) {
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
        [request addValue:[AppManager sharedManager].cookieStr forHTTPHeaderField:@"Cookie"];
        [webView loadRequest:request];
        self.currentUrl = URL;
        decisionHandler(WKNavigationActionPolicyCancel); // 必须实现 取消加载 不然会加载2遍
        return;
    } else {
        self.currentUrl = URL;
        decisionHandler(WKNavigationActionPolicyAllow); // 必须实现 加载
        return;
    }
}

- (BOOL)shouldAutorotate
{
    return YES;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    if (_portraitOrientation) {
        return UIInterfaceOrientationMaskPortrait;
    }
    
    return UIInterfaceOrientationMaskLandscape;
}

- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

@end
